package com.sunagy.demand.front.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * desc：#TODO fill me ！
 * author：三餘無夢生
 * date：2018/5/8
 * time：下午6:10
 */
public class TreeUtil {
    /**
     * 使用递归方法建树
     * @param treeNodes
     * @return
     */
    public static <T extends MyTreeNode> List<T> buildByRecursive(List<T> treeNodes,Integer rootId) {
        List<T> trees = new ArrayList<>();
        for (T treeNode : treeNodes) {
            if (treeNode.getFatherId()==rootId) {
                trees.add(findChildren(treeNode,treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     * @param treeNodes
     * @return
     */
    public static <T extends MyTreeNode> T findChildren(T treeNode,List<T> treeNodes) {
        for (T it : treeNodes) {
            if(treeNode.getId() ==it.getFatherId()) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<T>());
                }
                treeNode.getChildren().add(findChildren(it,treeNodes));
            }
        }
        return treeNode;
    }
}
